<template>
    <view class="w-screen h-screen flex flex-col" :style="themeColor()">
        <!-- #ifdef MP-WEIXIN || APP-PLUS -->
        <view :style="{'height':headerHeight}">
            <top-tabbar :data="param" :scrollBool="topTabarObj.getScrollBool()" class="top-header" />
        </view>
        <!-- #endif -->
        <view class="mx-[60rpx]">
            <view class="pt-[140rpx] text-[44rpx] font-500 text-[#333]">{{ t('findPassword') }}</view>
            <view class="text-[26rpx] leading-[39rpx] text-[var(--text-color-light6)] mt-[16rpx] mb-[80rpx]">{{ t('findPasswordTip') }}</view>
            <u-form labelPosition="left" :model="formData" errorType='toast' :rules="rules" ref="formRef">
                <view class="h-[88rpx] flex w-full items-center px-[30rpx] rounded-[var(--goods-rounded-mid)] box-border bg-[#F6F6F6]">
                    <u-form-item label="" prop="mobile" :border-bottom="false">
                        <u-input v-model="formData.mobile" type="number" maxlength="11" border="none"
                            :placeholder="t('mobilePlaceholder')" class="!bg-transparent"
                            :disabled="real_name_input" fontSize="26rpx"
                            placeholderClass="!text-[var(--text-color-light9)] text-[26rpx]"
                            @blur="onMobileBlur" />
                    </u-form-item>
                </view>
                
                <!-- 账号选择框 -->
                <view v-if="accountList.length > 0" class="mt-[20rpx]">
                    <view class="h-[88rpx] flex w-full items-center px-[30rpx] rounded-[var(--goods-rounded-mid)] box-border bg-[#F6F6F6]">
                        <u-form-item label="" prop="username" :border-bottom="false">
                            <view class="flex-1 flex items-center justify-between" @click="showAccountSelect = true">
                                <text v-if="formData.username" class="text-[26rpx] text-[#333]">{{ getSelectedAccountLabel() }}</text>
                                <text v-else class="text-[26rpx] text-[var(--text-color-light9)]">请选择账号</text>
                                <u-icon name="arrow-right" color="#b9b9b9" size="20"></u-icon>
                            </view>
                        </u-form-item>
                    </view>
                </view>
                
                <!-- 账号选择弹窗 -->
                <u-action-sheet :actions="accountSelectList" :show="showAccountSelect" 
                    :closeOnClickOverlay="true" :safeAreaInsetBottom="true"
                    @close="showAccountSelect = false" @select="onAccountSelect" />
                
                <view class="h-[88rpx] flex w-full items-center px-[30rpx] rounded-[var(--goods-rounded-mid)] box-border bg-[#F6F6F6] mt-[40rpx]">
                    <u-form-item label="" prop="mobile_code" :border-bottom="false">
                        <u-input v-model="formData.mobile_code" type="number" maxlength="4" border="none"
                            :placeholder="t('codePlaceholder')" class="!bg-transparent" :disabled="real_name_input"
                            fontSize="26rpx" placeholderClass="!text-[var(--text-color-light9)] text-[26rpx]">
                            <template #suffix>
                                <sms-code :mobile="formData.mobile" type="find_pass" v-model="formData.mobile_key"></sms-code>
                            </template>
                        </u-input>
                    </u-form-item>
                </view>
                <!-- <view class="h-[88rpx] flex w-full items-center px-[30rpx] rounded-[var(--goods-rounded-mid)] box-border bg-[#F6F6F6] mt-[40rpx]">
                    <u-form-item label="" prop="captcha_code" :border-bottom="false">
                        <u-input v-model="formData.captcha_code" border="none"
                            :placeholder="t('captchaPlaceholder')" class="!bg-transparent"
                            :disabled="real_name_input" fontSize="26rpx"
                            placeholderClass="!text-[var(--text-color-light9)] text-[26rpx]">
                            <template #suffix>
                                <image :src="captcha.image.value" class="h-[48rpx] w-[60rpx] ml-[20rpx]" mode="heightFix" @click="captcha.refresh()" />
                            </template>
                        </u-input>
                    </u-form-item>
                </view> -->
                <view class="h-[88rpx] flex w-full items-center px-[30rpx] rounded-[var(--goods-rounded-mid)] box-border bg-[#F6F6F6] mt-[40rpx]">
                    <u-form-item label="" prop="password" :border-bottom="false">
                        <u-input v-model="formData.password" border="none" :password="isPassword" maxlength="40"
                            :placeholder="t('passwordPlaceholder')" class="!bg-transparent"
                            :disabled="real_name_input" fontSize="26rpx"
                            placeholderClass="!text-[var(--text-color-light9)] text-[26rpx]">
                            <template #suffix>
                                <view @click="changePassword" v-if="formData.password">
                                    <u-icon :name="isPassword?'eye-off':'eye-fill'" color="#b9b9b9" size="20"></u-icon>
                                </view>
                            </template>
                        </u-input>
                    </u-form-item>
                </view>
                <view class="h-[88rpx] flex w-full items-center px-[30rpx] rounded-[var(--goods-rounded-mid)] box-border bg-[#F6F6F6] mt-[40rpx]">
                    <u-form-item label="" prop="confirm_password" :border-bottom="false">
                        <u-input v-model="formData.confirm_password" border="none" :password="isConfirmPassword"
                            maxlength="40" :placeholder="t('confirmPasswordPlaceholder')" class="!bg-transparent"
                            :disabled="real_name_input" fontSize="26rpx"
                            placeholderClass="!text-[var(--text-color-light9)] text-[26rpx]">
                            <template #suffix>
                                <view @click="changeConfirmPassword" v-if="formData.confirm_password">
                                    <u-icon :name="isConfirmPassword?'eye-off':'eye-fill'" color="#b9b9b9" size="20"></u-icon>
                                </view>
                            </template>
                        </u-input>
                    </u-form-item>
                </view>
            </u-form>
            <view class="mt-[160rpx]">
                <button class="w-full h-[80rpx] !bg-[var(--primary-color)] text-[26rpx] rounded-[40rpx] leading-[80rpx] font-500 !text-[#fff]" @click="handleConfirm">{{ t('confirm') }}</button>
            </view>
        </view>
    </view>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { t } from '@/locale'
import { resetPassword, getMemberListByMobile } from '@/app/api/system'
import { redirect, pxToRpx } from '@/utils/common'
import { useCaptcha } from '@/hooks/useCaptcha'
import { topTabar } from '@/utils/topTabbar'

let menuButtonInfo: any = {};
// 如果是小程序，获取右上角胶囊的尺寸信息，避免导航栏右侧内容与胶囊重叠(支付宝小程序非本API，尚未兼容)
// #ifdef MP-WEIXIN || MP-BAIDU || MP-TOUTIAO || MP-QQ
menuButtonInfo = uni.getMenuButtonBoundingClientRect();
// #endif
/********* 自定义头部 - start ***********/
const topTabarObj = topTabar()
let param = topTabarObj.setTopTabbarParam({ title: '', topStatusBar: { bgColor: '#fff', textColor: '#333' } })
/********* 自定义头部 - end ***********/
const headerHeight = computed(() => {
    return Object.keys(menuButtonInfo).length ? pxToRpx(Number(menuButtonInfo.height)) + pxToRpx(menuButtonInfo.top) + pxToRpx(8) + 'rpx' : 'auto'
})
const formData = reactive({
    mobile: '',
    mobile_key: '',
    mobile_code: '',
    // captcha_key: '',
    // captcha_code: '',
    password: '',
    confirm_password: '',
    username: ''
})
const captcha = useCaptcha(formData)
captcha.refresh()

// 账号列表相关
const accountList = ref<any[]>([])
const accountSelectList = ref<any[]>([])

const real_name_input = ref(true);
onMounted(() => {
    // 防止浏览器自动填充
    setTimeout(() => {
        real_name_input.value = false;
    }, 800)
});

const loading = ref(false)
const formRef: any = ref(null)
const isPassword = ref(true)
const isConfirmPassword = ref(true)

// 手机号失焦时查询账号列表
const onMobileBlur = async () => {
    if (formData.mobile && /^1[3-9]\d{9}$/.test(formData.mobile)) {
        try {
            const res: any = await getMemberListByMobile({ mobile: formData.mobile })
            if (res && res.data) {
                accountList.value = res.data
                // 转换为选择器需要的格式
                accountSelectList.value = res.data.map((item: any) => ({
                    name: item.username,
                    value: item.username,
                }))
            }
        } catch (error) {
            console.error('查询账号列表失败:', error)
            accountList.value = []
            accountSelectList.value = []
        }
    }
}

const showAccountSelect = ref(false)

const getSelectedAccountLabel = () => {
    const selected = accountSelectList.value.find(item => item.value === formData.username)
    return selected ? selected.name : ''
}

const onAccountSelect = (item: any) => {
    formData.username = item.value
    showAccountSelect.value = false
}

const changePassword = () => {
    isPassword.value = !isPassword.value
}

const changeConfirmPassword = () => {
    isConfirmPassword.value = !isConfirmPassword.value
}

const rules = {
    'username': {
        type: 'string',
        required: true,
        message: '请选择账号',
        trigger: ['blur', 'change']
    },
    'password': {
        type: 'string',
        required: true,
        message: t('passwordPlaceholder'),
        trigger: ['blur', 'change']
    },
    'mobile_code': {
        type: 'string',
        required: true,
        message: t('codePlaceholder'),
        trigger: ['blur', 'change']
    },
    // 'captcha_code': {
    //     type: 'string',
    //     required: true,
    //     message: t('captchaPlaceholder'),
    //     trigger: ['blur', 'change'],
    // },
    'confirm_password': [
        {
            type: 'string',
            required: true,
            message: t('confirmPasswordPlaceholder'),
            trigger: ['blur', 'change']
        },
        {
            validator(rule: any, value: any) {
                return value == formData.password
            },
            message: t('confirmPasswordError'),
            trigger: ['change', 'blur'],
        }
    ],
    'mobile': [
        {
            type: 'string',
            required: true,
            message: t('mobilePlaceholder'),
            trigger: ['blur', 'change'],
        },
        {
            validator(rule: any, value: any) {
                return uni.$u.test.mobile(value)
            },
            message: t('mobileError'),
            trigger: ['change', 'blur'],
        }
    ],
}

const handleConfirm = () => {
    formRef.value.validate().then(() => {
        if (loading.value) return
        loading.value = true

        resetPassword(formData).then((res: any) => {
            redirect({ url: '/app/pages/auth/login', mode: 'redirectTo' })
        }).catch(() => {
            loading.value = false
        })
    })
}
</script>

<style lang="scss" scoped>
:deep(.u-input) {
    background-color: transparent !important;
}

:deep(.u-checkbox) {
    margin: 0 !important;
}

:deep(.u-form-item) {
    flex: 1;

    .u-line {
        display: none;
    }
}
</style>
